<!-- 
   element文件上传封装组件
  -->
<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      :before-upload="beforeAvatarUpload"
      :on-error="handleAvatarError"
      :http-request="submitUploadImgUrl"
      :limit="1"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>
<script>
import axios from "axios";
export default {
  name: "uploadPdf",
  data() {
    return {
      url: process.env.VUE_APP_URL + "/sys/sysuser/upload",
      num: 0
    };
  },
  props: ["imageValue", "fileIndex"],
  mounted() {
    this.imageUrl = this.imageValue;
  },
  methods: {
    submitUploadImgUrl(uploader) {
      //  不做处理的方式
      let form = new FormData();
      form.append("file", uploader.file);
      axios
        .post(this.url, form, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          this.imageUrl = res.data.data.src;
          this.$emit("handlefileSuccess", this.imageUrl, uploader.file);
          //上传成功
          //处理自己的逻辑
          this.$message({
            type: "success",
            message: "上传成功！"
          });
        })
        .catch(() => {
          //上传失败
          //处理自己的逻辑
          this.$message({
            type: "error",
            message: "上传错误！"
          });
        });
    },
    beforeAvatarUpload(file) {
      // const isPDF = file.type === "application/pdf";
      const isLt5M = file.size / 1024 / 1024 < 1024;
      // if (!isPDF) {
      //   this.$message.error("上传文件只能是指定格式的文件!");
      // }
      if (!isLt5M) {
        this.$message.error("上传文件大小不能超过 1G!");
      }
      return isLt5M;
    },
    handleAvatarError() {
      this.$message({
        type: "error",
        message: "上传错误！"
      });
    }
  },
  watch: {
    "imageValue"(val) {
      this.imageUrl = val;
    },
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
